<?php
/**
 * Created by PhpStorm.
 * User: shkj
 * Date: 2020/4/22
 * Time: 23:35
 */

namespace app\api\model;


use think\Model;

class Type extends Model
{
    protected $hidden = ['id'];
    public function select(){
        $res = self::all();
        if($res){
            return_json(200,'查询成功',$res);
        }else{
            return_json(400,'查询失败');
        }
    }

    public function add($data)
    {

        $type = self::where('type_name', $data['type_name'])->find();
        if ($type) {
            return_json(400, '该类型已经存在');
        } else {
            $res = self::create($data);
            if ($res) {
                return_json(200, '添加成功');
            } else {
                return_json(400, '失败');
            }
        }
    }

    public function detail($id){
        $res = $this->where('id',$id)->find();
        if($res){
            return_json(200,'查询成功',$res);
        }else{
            return_json(400,'查询失败');
        }
    }

    public function del($id)
    {
        $del=db('type')->delete($id);
        // 删除商品类型下面的商品属性
        db('attr')->where(array('type_id'=>$id))->delete();
        if($del){
            return_json(200,'删除商品类型成功');
        }else{
            return_json(400,'删除商品类型失败！');
        }
    }

    public function modify($data)
    {
        $type = self::where('type_name', $data['type_name'])->where('id', '<>', $data['id'])->find();
        if ($type) {
            return_json(400, '该类型已经存在');
        } else {
            $type = self::where('id', $data['id'])->update($data);
            if ($type) {
                return_json(200, '修改成功');
            } else {
                return_json(400, '修改失败');
            }
        }
    }

}